<template>
  <div class="page-header-index-wide">
    <a-row :gutter="24">
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="月销售额" :total="monthXiao">
          <a-tooltip title="指标说明" slot="action">
            <a-icon type="info-circle-o"/>
          </a-tooltip>
          <div>
            <!-- <trend flag="up" style="margin-right: 16px;">
              <span slot="term">周同比</span>
              12%
            </trend>
            <trend flag="down">
              <span slot="term">日同比</span>
              11%
            </trend>-->
          </div>
          <template slot="footer">
            日均销售额
            <span>￥ {{dayXiao}}</span>
          </template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="访问量" :total="8846 | NumberFormat">
          <a-tooltip title="指标说明" slot="action">
            <a-icon type="info-circle-o"/>
          </a-tooltip>
          <div>
            <mini-area/>
          </div>
          <template slot="footer">
            日访问量
            <span>{{ '1234' | NumberFormat }}</span>
          </template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="本周支付笔数" :total="ordersVO.totalOrders | NumberFormat">
          <div>
            <mini-bar :height="40" ref="miniBar"/>
          </div>
          <template slot="footer">
            转化率
            <span>{{ordersVO.orderConversionRate}}%</span>
          </template>
        </chart-card>
      </a-col>

      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="当月核销笔数" :total="heXiaoCount">
          <div>
            <mini-progress color="rgb(19, 194, 194)" :target="80" :percentage="78" :height="8"/>
          </div>
          <template slot="footer">
            <trend style="margin-right: 16px;">
              <span slot="term"></span>
            </trend>
            <trend>
              <span slot="term"></span>
            </trend>
          </template>
        </chart-card>
      </a-col>
    </a-row>

    <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}">
      <div class="salesCard">
        <a-tabs
          default-active-key="1"
          size="large"
          :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}"
        >
          <div class="extra-wrapper" slot="tabBarExtraContent">
            <div class="extra-item">
              <a-radio-group :value="barType" @change="statisticst">
                <a-radio-button value="year">按年统计</a-radio-button>
                <a-radio-button value="month">按月统计</a-radio-button>
                <a-radio-button value="week">按周统计</a-radio-button>
              </a-radio-group>
            </div>
            <a-range-picker
              :ranges="{ '今日': [moment().startOf('day'), moment().endOf('day')],
                     '本周': [moment().startOf('week'), moment().endOf('week')],
                     '本月': [moment().startOf('month'), moment().endOf('month')] }"
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              @ok="getStartTimeAndEndTime"
            />
          </div>
          <a-tab-pane tab="柱状图" key="1">
            <a-row :gutter="24">
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <div id="myChart" :style="{width: '1300px', height: '400px'}"></div>
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="门店销售排行榜" :list="rankList"/>
              </a-col>
              <div></div>
            </a-row>
          </a-tab-pane>
          <a-tab-pane tab="订单情况" key="2">
            <a-row>
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <!-- <order-pie-chart></order-pie-chart> -->
                <div id="myPai" :style="{width: '500px', height: '500px'}"></div>
                <!-- <bar title="销售额趋势" :dataSource="barData"/> -->
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="门店销售排行榜" :list="rankList"/>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>

    <a-row>
      <a-col :span="24">
        <a-card
          :loading="loading"
          :bordered="false"
          title="最近一周访问次数统计"
          :style="{ marginTop: '24px' }"
        >
          <a-row>
            <a-col :span="6">
              <head-info title="今日访问IP数" :content="loginfo.todayIp"></head-info>
            </a-col>
            <a-col :span="2">
              <a-spin class="circle-cust">
                <a-icon slot="indicator" type="environment" style="font-size: 24px"/>
              </a-spin>
            </a-col>
            <a-col :span="6">
              <head-info title="今日访问次数" :content="loginfo.todayVisitCount"></head-info>
            </a-col>
            <a-col :span="2">
              <a-spin class="circle-cust">
                <a-icon slot="indicator" type="team" style="font-size: 24px"/>
              </a-spin>
            </a-col>
            <a-col :span="6">
              <head-info title="访问总次数" :content="loginfo.totalVisitCount"></head-info>
            </a-col>
            <a-col :span="2">
              <a-spin class="circle-cust">
                <a-icon slot="indicator" type="rise" style="font-size: 24px"/>
              </a-spin>
            </a-col>
          </a-row>
          <line-chart-multid :fields="visitFields" :dataSource="visitInfo"></line-chart-multid>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
  import OrderPieChart from '@/views/echarts/OrderPieChart'
  import ChartCard from '@/components/ChartCard'
  import ACol from "ant-design-vue/es/grid/Col"
  import ATooltip from "ant-design-vue/es/tooltip/Tooltip"
  import MiniArea from '@/components/chart/MiniArea'
  import MiniBar from '@/views/echarts/MiniBar'
  import MiniProgress from '@/components/chart/MiniProgress'
  import RankList from '@/components/chart/RankList'
  import Bar from '@/components/chart/Bar'
  import LineChartMultid from '@/components/chart/LineChartMultid'
  import HeadInfo from '@/components/tools/HeadInfo.vue'
  import Pie from '@/components/chart/Pie'
  import Trend from '@/components/Trend'
  import { getLoginfo,getVisitInfo } from '@/api/api'
  import { getAction } from '@/api/manage'
  import moment from 'moment';
  const rankList = []
  // for (let i = 0; i < 20; i++) {
  //   rankList.push({
  //     name: '白鹭岛 ' + (i+1) + ' 号店',
  //     total: 1234.56 - i * 100
  //   })
  // }
  const barData = []
  for (let i = 0; i < 12; i += 1) {
    barData.push({
      x: `${i + 1}月`,
      y: Math.floor(Math.random() * 1000) + 200
    })
  }
  export default {
    name: "Analysis",
    components: {
      ATooltip,
      ACol,
      ChartCard,
      MiniArea,
      MiniBar,
      MiniProgress,
      RankList,
      Bar,
      Trend,
      LineChartMultid,
      HeadInfo,
      Pie,
      OrderPieChart
    },
    data() {
      return {
        monthXiao:"0",
        dayXiao:"0",
        heXiaoCount:"0",
        ordersVO:{},
        startTime:'',
        endTime:'',
        loading: true,
        center: null,
        rankList,
        barData,
        loginfo:{},
        visitFields:['ip','visit'],
        visitInfo:[],
        indicator: <a-icon type="loading" style="font-size: 24px" spin />,
        // 查询条件
        queryParam: {},
        // 数据集
        countSource: [],
        // 柱状图
        barType: 'year',
        barDateY: [],
        barDateX:[],
        barValue: [],
        // 饼状图
        pieType: 'year',
        pieDate: ['month', 'month'],
        pieValue: [],
        // 统计图类型
        tabStatus: 'bar',
        url: {
          getYearCountInfo: '/statistics-api/payChart/merchant/monthofYear',
          getMonthCountInfo: '/statistics-api/payChart/merchant/monthofYear',
          getweekCountInfo: '/statistics-api/payChart/merchant/monthofYear',
          getCabinetCountInfo: '/api/report/getCabinetCountInfo'
        }
      }
    },
    mounted() {
      this.getZiFuData()
      this.getHeXiaoCount()
      this.drawLine()
     
    },
    beforeUpdate(){
    this.drawLine()
     this.getData(this.startTime,this.endTime)
     // this.drawLine()
    },
    created() {
      let url = this.url.getYearCountInfo
      this.loadDate(url, 'year', {  type: 4 })
      setTimeout(() => {
        this.loading = !this.loading
      }, 1000)
      this.initLogInfo();
      this.getMonthofDayXiao()
      this.getRightRanking()
    },
    methods: {
      getZiFuData() {
        let this_ = this;
        this.$nextTick(function () {
          getAction("/statistics-api/orderChart/getOrderConversionRate")
            .then(res => {
              if (res.success) {
                //遍历数组，取出数据
                for (let key in res.data) {
                  if(key == 'ordersVO'){
                    this_ .ordersVO = res.data[key]
                  }
                }
              } else {
                this_.$message.warn("无结果");
              }
            })
            .catch(err => {
            });
        })
      },
      getHeXiaoCount(){
        let this_ = this
        getAction("/statistics-api/orderChart/getOrderCancellationData").then(res => {
          if (res.success) {
            this_.heXiaoCount = res.data.toString()
          } else {
            let that = this
            that.$message.warning(res.message)
          }
        })
      },
      getMonthofDayXiao(){
        let this_ = this
        let month={type:3}
        let day={type:1}
        getAction("/statistics-api/payChart/merchant/dayofmonth",month).then(res =>{
          if(res.success){
            this_.monthXiao=res.result.data[0].presentPrice.toString()
          }else{
            let that = this
            that.$message.warning(res.message)
          }
        })
        getAction("/statistics-api/payChart/merchant/dayofmonth",day).then(res =>{
      if(res.success){
        this_.dayXiao=res.result.data[0].presentPrice.toString()
      }else{
        let that = this
        that.$message.warning(res.message)
      }
        })
      },
      //右边排行榜
      getRightRanking(){
        let this_ = this
        let month={type:3}
        getAction("/statistics-api/payChart/merchant/rightmonth",month).then(res =>{
            if(res.success){
              for(let key in res.result){
                this.rankList.push({
                  name:res.result[key].shopName,
                  total:res.result[key].presentPrice
                })
              }
            }
        })
      },
        moment,
        getStartTimeAndEndTime(dates){
          this.startTime = moment(dates[0]._d).format('YYYY-MM-DD HH:mm:ss')
          this.endTime = moment(dates[1]._d).format('YYYY-MM-DD HH:mm:ss')
          this.getData(this.startTime,this.endTime);
        },
        drawmyPai(statusName,data){
          // 基于准备好的dom，初始化echarts实例
          let myPai = this.$echarts.init(document.getElementById('myPai'))
          // 绘制图表
          myPai.setOption({
            title : {
              // text: '订单情况',
              subtext: '',
              x:'center'
            },
            tooltip : {
              trigger: 'item',
              formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              data: statusName
            },
            series : [
              {
                name: '',
                type: 'pie',
                radius : '55%',
                center: ['50%', '60%'],
                data:data,
                itemStyle: {
                  emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          });
        },
        getData(startTime,endTime) {
          if(startTime == '' && endTime == ''){
            startTime = moment().startOf('month').format("YYYY-MM-DD HH:mm:ss");
            endTime = moment().endOf('month').format("YYYY-MM-DD HH:mm:ss");
          }
          let this_ = this;
          this.$nextTick(function () {
            getAction("/statistics-api/orderChart/pieChart",{startTime,endTime})
              .then(res => {
                if (res.success) {
                    //遍历数组，取出数据
                    let statusName=[],data=[],obj={}
                  for (let key in res.data) {
                    statusName.push(key);
                    obj = {value:res.data[key],name:key};
                    data.push(obj);
                  }
                    this_.drawmyPai(statusName,data);
                  } else {
                    this_.drawmyPai([], [], [],[]);
                    this_.$message.warn("无结果");
                }
              })
              .catch(err => {
              });
          })
        },
      // 以下为销售额用到的方法
      loadDate(url, type, param) {
        getAction(url, param).then(res => {
          if (res.success) {
            this.countSource = []
            if (type === 'year') {
              this.getYearCountSource(res.result)
            }
            if (type === 'month') {
              this.getMonthCountSource(res.result)
            }
            if (type === 'week') {
              this.getWeekCountSource(res.result)
            }
          } else {
            var that = this
            that.$message.warning(res.message)
          }
        })
      },
      getYearCountSource(data) {
        console.log('年回调')
        this.barDateX = []
        this.barDateY =[]
        for(let key in data){
          this.barDateX.push(key)
          this.barDateY.push(data[key])
        }
        this.drawLine()

      },
      getMonthCountSource(data) {
        console.log('月回调')
        this.barDateX = []
        this.barDateY =[]
        for(let key in data){
          this.barDateX.push(key)
          this.barDateY.push(data[key])
        }
        this.drawLine()
      },
      getWeekCountSource(data) {
        console.log('周回调')
        this.barDateX = []
        this.barDateY =[]
        
        this.barDateX.push(
            `星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`,`星期日`)
        for(let key in data){
          this.barDateY.push(data[key])
        }
        this.drawLine()
      },
    
      // 选择统计图类别----1
      callback(key) {
        if (key === '1') {
          this.tabStatus = 'bar'
          this.queryDatebar()
        } else {
          this.tabStatus = 'pie'
          this.queryDatepie()
        }
      },
      // 选择统计类别  ----a
      statisticst(e) {
        if (this.tabStatus === 'pie') {
          this.pieType = e.target.value
          this.queryDatepie()
        } else {
          this.barType = e.target.value
          this.queryDatebar()
        }
      },
      // 按月（年,周）份查询----2 b 给url写参数
      queryDatebar() {
        if (this.barType === 'year') {
            this.getUrl(this.barType, {  type: 4 })
          } else if(this.barType === 'month') {
            this.getUrl(this.barType, {  type: 3 })
          }else if(this.barType === 'week'){
            this.getUrl(this.barType, {  type: 2 })
          }
      },
      queryDatepie() {
        if (this.barType === 'year') {
            this.getUrl(this.barType, {  type: 4 })
          }  else if(this.barType === 'month') {
            this.getUrl(this.barType, {  type: 3 })
          }else if(this.barType === 'week'){
            this.getUrl(this.barType, {  type: 2 })
          }
      },
      //查询时间
      searchReset() {
        console.log(this.tabStatus)
        if (this.tabStatus === 'pie') {
          this.pieValue = []
        } else {
          this.barValue = []
        }
        this.getUrl(this.barType, {})
      },
      // 选择请求url
      getUrl(type, param) {
        console.log('输出参数' + JSON.stringify(param))
        let url = ''
        if (type === 'year') {
          url = this.url.getYearCountInfo
        }
        if (type === 'month') {
          url = this.url.getMonthCountInfo
        }
        if (type === 'week') {
          url = this.url.getweekCountInfo
        }
        if (type === 'cabinet') {
          url = this.url.getCabinetCountInfo
        }
        this.loadDate(url, type, param)
      },
      // 选择月份日期
      handleBarDate(value, mode) {
        this.barValue = value
        this.barDate = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]]
      },
      handlePieDate(value, mode) {
        this.pieValue = value
        this.pieDate = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]]
      },
      drawLine() {
      var echarts = require('echarts')
      var myChart = echarts.init(document.getElementById('myChart'))
      myChart.setOption({
        title: {
          text: '   商店收益报表统计'
        },
        tooltip: {},
        xAxis: {
          data: this.barDateX
        },
        yAxis: {},
        series: [
          {
            name: '销售额',
            type: 'bar',
            data: this.barDateY
          }
        ]
      })
    },
    //以上为销售额用到的方法
    initLogInfo () {
      getLoginfo(null).then((res)=>{
        if(res.success){
          Object.keys(res.result).forEach(key=>{
            res.result[key] =res.result[key]+""
          })
          this.loginfo = res.result;
        }
      })
      getVisitInfo().then(res=>{
        if(res.success){
            console.log("aaaaaa",res.result)
            this.visitInfo = res.result;
          }
        })
    },
    },
  }
</script>

<style lang="scss" scoped>
.rank {
  height: 350px !important;
  overflow: auto !important;
}
.circle-cust {
  position: relative;
  top: 28px;
  left: -100%;
}
.extra-wrapper {
  line-height: 55px;
  padding-right: 24px;

  .extra-item {
    display: inline-block;
    margin-right: 24px;

    a {
      margin-left: 24px;
    }
  }
}

/* 首页访问量统计 */
.head-info {
  position: relative;
  text-align: left;
  padding: 0 32px 0 0;
  min-width: 125px;

  &.center {
    text-align: center;
    padding: 0 32px;
  }

  span {
    color: rgba(0, 0, 0, 0.45);
    display: inline-block;
    font-size: 0.95rem;
    line-height: 42px;
    margin-bottom: 4px;
  }
  p {
    line-height: 42px;
    margin: 0;
    a {
      font-weight: 600;
      font-size: 1rem;
    }
  }
}
</style>